package org.example.taskmaster.fragments;

import java.util.Calendar;

import org.example.taskmaster.R;
import org.example.taskmaster.activities.MainActivity;
import org.example.taskmaster.database.DatabaseAdapter;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class EditTaskFragment extends DetailsFragment implements OnDateSetListener, OnTimeSetListener, OnClickListener {
	
	// references to form views
	private TextView mNameText;
	private Spinner mListSpinner;
	private EditText mNotesText;
	private Long mRowId;
	private TextView mDateDisplay;
	private TextView mTimeDisplay;
	private Button mPickDate;
	private Button mPickTime;
	private Button mSaveTask;
	private int mYear;
	private int mMonth;
	private int mDay;
	private int mHour;
	private int mMinute;
	private int mComplete;
	// spinner listener - remove later
	public class MyOnItemSelectedListener implements OnItemSelectedListener {
		public void onItemSelected (AdapterView<?> parent, View view, int pos, long id) {
			Cursor c = (Cursor)parent.getItemAtPosition(pos);
			String item = c.getString(c.getColumnIndex("name"));
			// does nothing 
		}
		public void onNothingSelected(AdapterView parent) {
			// does nothing
		}
	}

	// Constructors
	/*
	 * No arguments for new task
	 */
	public EditTaskFragment() {
		this(null);
	}
	/*
	 * give rowId for edit task
	 */
	public EditTaskFragment(Long rowID) {
		type = "EditTask";
		mRowId = rowID;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (container == null) {
			return null;
		}
		// set edittask_fragment_layout.xml as the layout for this fragment
		View mainView = inflater.inflate(R.layout.edittask_fragment_layout, container, false);
		
        // get database
		dbAdapter = new DatabaseAdapter(getActivity());
		dbAdapter.open();
		
        // get references to form widgets
		mNameText = (TextView) mainView.findViewById(R.id.edittask_edit_name);
		mNotesText = (EditText) mainView.findViewById(R.id.edittask_edit_notes);
		mDateDisplay = (TextView) mainView.findViewById(R.id.dateDisplay);
		mTimeDisplay = (TextView) mainView.findViewById(R.id.timeDisplay);
		mPickDate = (Button) mainView.findViewById(R.id.pickDate);
		mPickTime = (Button) mainView.findViewById(R.id.pickTime);
		mListSpinner = (Spinner) mainView.findViewById(R.id.edittask_spinner);
		mSaveTask = (Button) mainView.findViewById(R.id.edittask_edit_save);
		
		// registers self as listener for the Save Task, Select Time, and Select Date buttons
		mSaveTask.setOnClickListener(this);
		mPickDate.setOnClickListener(this);
		mPickTime.setOnClickListener(this);

		// get current date and time
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		mHour = c.get(Calendar.HOUR_OF_DAY);
		mMinute = c.get(Calendar.MINUTE);
		
		// display date and time
		updateDate();
		updateTime();
		
		// fill list spinner with names of lists from database
		Cursor cursor = dbAdapter.fetchAllLists();
		String[] from = new String[] {DatabaseAdapter.KEY_LISTNAME};
		int[] to = new int[] {android.R.id.text1};
		SimpleCursorAdapter SCadapter = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_spinner_item, cursor, from, to);
		SCadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);		
		mListSpinner.setAdapter(SCadapter);
		mListSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
		
		// if this page was loaded with the rowID of a task to edit, populateFields() will fill in the form with that task's info
		populateFields();       
		
		return mainView;
	}
	/*
	 * If editing an existing task, this method will populate the form with the task's information.
	 */
	private void populateFields() {
		if (mRowId != null) {
			Cursor taskCursor = dbAdapter.fetchTask(mRowId);
			//startManagingCursor(taskCursor);

			mNameText.setText(taskCursor.getString(taskCursor
					.getColumnIndexOrThrow(DatabaseAdapter.KEY_NAME)));
			mNotesText.setText(taskCursor.getString(taskCursor
					.getColumnIndexOrThrow(DatabaseAdapter.KEY_NOTES)));
			mListSpinner.setSelection(0); //TODO: need to find an index which matches to a given String. 
			mYear = taskCursor.getInt(taskCursor
					.getColumnIndexOrThrow(DatabaseAdapter.KEY_YEAR));
			mMonth = taskCursor.getInt(taskCursor
					.getColumnIndexOrThrow(DatabaseAdapter.KEY_MONTH));
			mDay = taskCursor.getInt(taskCursor
					.getColumnIndexOrThrow(DatabaseAdapter.KEY_DAY));
			mHour = taskCursor.getInt(taskCursor
					.getColumnIndexOrThrow(DatabaseAdapter.KEY_HOUR));
			mMinute = taskCursor.getInt(taskCursor
					.getColumnIndexOrThrow(DatabaseAdapter.KEY_MINUTE));

			updateDate();
			updateTime();
		}
	}
	private void updateDate() {
		// generates date text from date values, overrides text set in XML
		mDateDisplay.setText( new StringBuilder()
				.append(mMonth+1).append("-")
				.append(mDay).append("-")
				.append(mYear).append(" "));
	}
	private void updateTime() {
		// generates time text from time values, overrides text set in XML
		mTimeDisplay.setText( new StringBuilder()
				.append(pad(mHour)).append(":")
				.append(pad(mMinute)).append(" "));
	}
	private static String pad(int c) {
	    if (c >= 10)
	        return String.valueOf(c);
	    else
	        return "0" + String.valueOf(c);
	}
	/*
	 * Saves a task to the database.
	 */
	private void saveState() {
		// Get content of forms
		String name = mNameText.getText().toString();
		Cursor c = (Cursor) mListSpinner.getSelectedItem();
		String list = c.getString(c.getColumnIndex("name")).trim();

		String notes = mNotesText.getText().toString();
		Toast.makeText(getActivity().getApplicationContext(), "List:" + list, Toast.LENGTH_SHORT).show();
		// catch null list
		if (list == null) list = "";
		
		// Determine whether this is a new task or an existing task being edited
		if (mRowId == null) {
			// Creating a new task
			long id = dbAdapter.createTask(name, list, notes, mYear, mMonth + 1, mDay,mHour,mMinute,0);
			if (id > 0) {
				mRowId = id;
			}
		} else {
			// Editing an existing task
			dbAdapter.updateTask(mRowId, name, list, notes, mYear, mMonth + 1, mDay,mHour,mMinute,0);
		}
	}
	@Override
	public void onDateSet(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		mYear = year;
		mMonth = monthOfYear;
		mDay = dayOfMonth;
		updateDate();

	}
	@Override
	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
		mHour = hourOfDay;
		mMinute = minute;
		updateTime();
	}

	@Override
	public void onClick(View v) {
    	switch (v.getId()) {
    	case R.id.pickDate:
			// shows date picker dialog box, then returns to New Task layout
			FragmentTransaction ft = getFragmentManager().beginTransaction();
			//Fragment prev = getFragmentManager().findFragmentByTag("dialog");
			DialogFragment newFragment = new DatePickerDialogFragment(this, mYear, mMonth, mDay);
			newFragment.show(ft, "dialog");
    		break;
    	case R.id.pickTime:
			// shows time picker dialog box, then returns to New Task layout
			//FragmentTransaction ft2 = getFragmentManager().beginTransaction();
			//Fragment prev = getFragmentManager().findFragmentByTag("dialog");
			TimePickerDialogFragment timeFragment = new TimePickerDialogFragment(getActivity(),this, mHour, mMinute, true);
			//timeFragment.show(ft2, "timedialog");
			timeFragment.show();
    		break;

    	case R.id.edittask_edit_save:
    		// save the task, then load list view for new task's list
    		saveState();
    		Cursor c = (Cursor) mListSpinner.getSelectedItem();
    		String list = c.getString(c.getColumnIndex("name"));

    		// refer to MainActivity to load a fragment into details area
    		MainActivity main = (MainActivity) getActivity();
    		main.showTaskList(list);
    		break;
    	}

	}

}
